package top.kaoshanji.p2ch10b;

import java.io.*;
import java.util.Calendar;
import java.util.Date;

/**
 * 代码清单-p2ch10b-328页a：版本更新后的序列化机制的实现
 * author kaoshanji
 * ^_^
 * create time 2025/2/3 11:04
 */
public class NewUser implements Serializable {

    private transient Date birthDate;

    public NewUser(Date birthDate) {
        this.birthDate = birthDate;
    }

    public int getAge() {
        return dateToAge(birthDate);
    }

    // 年龄转换成日期
    private Date ageToDate(int age) {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        int newYear = currentYear - age;
        calendar.set(Calendar.YEAR, newYear);
        return calendar.getTime();
    }

    // 日期转换成年龄
    private int dateToAge(Date date) {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        calendar.setTime(birthDate);
        int birthYear = calendar.get(Calendar.YEAR);
        return currentYear - birthYear;
    }


    private void writeObject(ObjectOutputStream output) throws IOException {
        output.defaultWriteObject();
        int age = dateToAge(birthDate);
        output.writeInt(age);
        System.out.println(age);
    }

    // 对象完整性验证的示例
    // 应该是 private，但是在 package-info.java 里面会显示红线
    public void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
        input.defaultReadObject();
        int age = input.readInt();
        this.birthDate = ageToDate(age);

        // 具体逻辑在 UserValidator 类
        input.registerValidation(new UserValidator(this), 0);
    }

    private static class UserValidator implements ObjectInputValidation {

        private NewUser user;

        public UserValidator(NewUser user) {
            this.user = user;
        }

        @Override
        public void validateObject() throws InvalidObjectException {
            if (user.getAge() < 0) {
                throw new InvalidObjectException("非法的年龄数值。");
            }

        }
    }

}
